#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   Set_up.py
@Time    :   2025/03/26 18:00:00
@Author  :   yangliang 
@Version :   1.0
@Contact :   yangl@genvict.com
@License :   (C)Copyright 2022-2025
@Desc    :   None
'''
# here put the import lib

import datetime
import  os
from ssl import CHANNEL_BINDING_TYPES
from xml.dom.expatbuilder import FilterVisibilityController

from sympy import EX
from commDriver.zlg.zlgcan import *



# HW config
#CAN
drive_type = 'USE_TS_TC1013_DEVICE'     # 同星CAN
CAN_Type = 'CANFD'
if CAN_Type == 'CAN':
    configure_baudrate = {'CAN_Type':'CAN','ArbRate':500,'DataRate':500,'TermResistor':True}
else:
    configure_baudrate = {'CAN_Type':'CANFD','ArbRate':500,'DataRate':2000,'TermResistor':True}

#drive_type = ZCAN_USBCANFD_200U        #周立功CAN
# drive_index = 0
# chn_index = 0
# can_abit = 500000
# can_bbit = 2000000

# can_Type = 'CANFD'


power_Type = 'IT6720' # 2303 or IT6720
gpib_address = 'GPIB0::16::INSTR'

M600Tport = 'COM8'
M600Tbaudrate = 115200
M600TTimeOut = 1


#Dbc define
root = os.getcwd()
project_DBC_File_CAN = os.path.join(root, r'data\SHA_EP_BCAN3_Matrix_V1.0.0_20250315.dbc')
blfname = datetime.datetime.now().strftime('%y%m%d') + '.blf'
project_BLF_File_CAN = os.path.join(root, fr"blf\{blfname}")
# project_DBC_File_CAN = os.path.join(root, r'data\FX12_Matrix_CRRL_V1.6_20220531.dbc')
NetName = 'SHA_EP_BCAN3'
nodeName= 'VIU0'
EnableNode = ['ETC','VIU0','EWS_F']

#Power Config
source='Power'           #电源名称,可以使用NIMAX查看
baudrate=9600

#Dbc UDS
reqID = 0x750
resID = 0x7D0
AFctID = 0x7DF


jidianqiPort = 'COM4'
jidianqiBaudrate = 9600
jidianqiTimeOut = 0.3

CanPrint = True

vinAes = []
testVin = []
CalcCMAC = True

def string_to_hex(input_str, length=None, pad_char='\x20', encoding='ASCII'):
    """通用字符串转十六进制函数
    Args:
        input_str: 输入字符串
        length: 目标字节长度
        pad_char: 填充字符（默认空格）
        encoding: 编码类型（ASCII/BCD）
    """
    # ASCII编码处理
    if encoding == 'ASCII':
        padded = input_str.ljust(length, pad_char)
        return bytes(padded, 'ascii').hex(' ').upper()
    
    # BCD编码处理
    if encoding == 'BCD':
        if not input_str.isdigit():
            raise ValueError("BCD input must be numeric")
        padded = input_str.zfill(length*2)
        return ''.join(f"{int(padded[i:i+2]):02X}" for i in range(0, len(padded), 2))
    
    raise ValueError("Unsupported encoding type")
# 0x22 DID
# ECU名称(F197 DID) - 10字节
EcuName_hex = string_to_hex('ETCM', 10)
# 整车厂ECU硬件版本号(F089 DID) - 5字节
EcuHardwareVersionNumber_hex = string_to_hex('V1.01', 5) 
# 整车厂ECU软件版本号(F189 DID) - 15字节
EcuSoftwareVersionNumber_hex = string_to_hex('02.04.01_250818', 15)
# BootLoader软件版本号(F180 DID) - 12字节
BootLoaderSoftwareVersionNumber_hex = string_to_hex('boot_v1.3.2', 12, pad_char='\x00')
# 软件识别码(F0FA DID) - 9字节
SoftwareIdentificationCode_hex = string_to_hex('BOD03A001', 9)
# ECU软件版本号(F07F DID) - 9字节
ECUSoftwareVersionNumberDataIdentifier_hex = string_to_hex('V1.0.3_250818', 9)
# 整车厂定义零件号(F187 DID) - 16字节
VehicleFactoryDefinedPartNumber_hex = string_to_hex('ETCM01A001', 16)
# 整车厂定义软件零件号(F013 DID) - 16字节
VehicleFactoryDefinedSoftwarePartNumber_hex = string_to_hex('13120217', 16) #13120113 11961764
# 应用软件指纹信息(F184 DID) - 19字节
SoftwareFingerprintInformation_hex = '19 04 16' + string_to_hex('OTA001', 16)
# 供应商定义ECU硬件版本号(F193 DID) - 26字节
SupplierDefinedECUHardwareVersionNumber_hex = string_to_hex('V1.0_20250314', 16, pad_char='\x20')
# 供应商定义ECU软件版本号(F195 DID) - 21字节'
SupplierDefinedECUSoftwareVersionNumber_hex = string_to_hex('V1.0.3_250818', 21, pad_char='\x20')
# 供应商代码(F18A DID) - 10字节
SupplierCode_hex = string_to_hex('18004148', 10, pad_char='\x20')
# ECU生产日期(F18B DID) - 4字节
ECUProductionDate = string_to_hex('00', 4, encoding='BCD')
# 精确追溯码(F18C DID) - 36字节
ExactTraceCode_hex = string_to_hex('12120148718004148L125408A00008888', 36, pad_char='\x00', encoding='ASCII')
# 车辆识别号(F190 DID) - 17字节 默认全零
VINDataIdentifier_hex = '01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 11 12'
# 刷写尝试计数器(F0F1 DID) - 4字节
FlashWriteAttemptCounter_hex = string_to_hex('00', 4, encoding='BCD')
# 编程依赖检查成功计数器(F0F3 DID) - 4字节
ProgrammingDependencyCheckSuccessCounter_hex = string_to_hex('00', 4, encoding='BCD')
# 电控单元配置文件号(F1A9 DID) - 5字节
ElectricalControlUnitConfigurationFileNumber_hex = string_to_hex('V1.1', 5)
# 整车软件版本号(F0FF DID) - 64字节
VehicleSSoftwareVersionNumber_hex = string_to_hex('01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10', 64)
# 应用程序内部版本号 7800 16字节
APP_internal_version_hex = string_to_hex('V1.0.3_250808', 16)
# 引导程序内部版本号 7801 16字节
BOOT_internal_version_hex = string_to_hex('V1.00.01', 16)

# OBU ID 7802 4字节
OBU_ID_hex = string_to_hex('88888888', 4, encoding='BCD')
# OBU SN 7803 16字节
OBU_SN_hex = string_to_hex('1234567898765432', 16)
# 蓝牙名称 7804 16字节
OBU_BluetoothName_hex = string_to_hex('ETC-JY-8888', 20, encoding='ASCII')


OBU_Software_Version = 'V1.0.3_250818'

# 是否拦截流控帧发送
is_block_flow_control = False


# softname = 'MRR_HKHAU_HaiWai_App_1.00.01_Boot_1.1_CT_6.1.43.2_6.1.43.2_Pro.XCDII.zip'

# zipfile_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' +softname
# error_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' +'FailedSwPlus.zip'
# oldzipfile_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' +'old.zip'
# errorApp_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' +'FailedSwPlus\\001_Failed_App.hex'
# errorBoot_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' +'FailedSwPlus\\002_Failed_Boot.hex'

flashDriverPath = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' + 'Flash_drv20250818.s19'
soft_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' + 'APP_ES39ETC20250818.s19'
bin_path = os.path.abspath(os.path.join(os.getcwd(),"./sw")) + '\\' + 'OBUC513_App_V1.0.3_20250818.bin'
bin_Offset = 0x0

CTBoot=[6,1,43,2]

'''BYD产品DID'''
# 硬件版本号 F193 
ECUHardwareVersionNumber = '0c 18 03 05 00'# 美信【01 16 09 06 00】      70331【0b 17 09 0d 00】  4323【05 16 0c 1f 00 】 9840【06 16 0c 1f 00 】 '0b 17 0a 08 00':'MPC_70331_230Pro',
# 软件编码 F194
ECUSoftwareCode = '4A550013B870000000'
# DATASET软件序列号 FF94
DATASETSoftwareNumber = []
# DATASET软件版本号 FF95
DATASETSoftwareVersionNumber = []
# 底层软件Bootload版本号 F180
bootyear = [24]
bootmonth = [11]
bootday = [28]
bootchangeNum = [0]
bootver = [11]
bootweek = [48]
# bootweek.append(datetime.date(2000 + bootyear[0], bootmonth[0], bootday[0]).isocalendar().week)
VehicleManufacturerECUBootSoftwareVersionNumber = [0x62,0xF1,0X80] + bootyear + bootweek + bootchangeNum + bootver + [0] + [0] + bootyear + bootmonth + bootday

# 软件版本号 F195
APP_ver = '10001'
softver = []
hexver = hex(int(APP_ver)).replace('0x','').zfill(4)
softver.append(int(hexver[0:2],16))
softver.append(int(hexver[2:4],16))
softyear =[24]
softmonth = [11]
softday = [28]
ECUSoftwareVersionNumber = softver + softyear + softmonth + softday + [0]

# 生产模式 3401
FactoryMode = []
# 配置字
VariantCoding = [   ('13 B8 70 01 40 80 07 56'),               
                ]

# 初始存在故障
InitialFailure = [[0xA1,0x43,0x50,0x09]]


Dut_Type = 'ES39'

DTC_list = [    ([0x91,0x17,0x16],'Votage Low Error'),			
                ([0x91,0x17,0x17],'Votage High Error'),	
                ([0xC0,0x77,0x88],'TBOX CAN BusOff'),
                ([0xC2,0x6C,0x87],'VIU Nodemissing'),	
				([0xA1,0x40,0x46],'EEPROM Fault'),	
                ([0xA1,0x40,0x49],'BT Fault'),		
				([0xA1,0x41,0x49],'ESAM Fault'),
                ([0xA1,0x42,0x49],'DSRC Fault'),
                ([0xA1,0x43,0x50],'UNFIX'),			
            ]

DTC_list2 = {   'Votage Low Error':     [0x91,0x17,0x16],	
                'Votage High Error':    [0x91,0x17,0x17],
                'TBOX CAN BusOff':      [0xC0,0x77,0x88],
                'VIU Nodemissing':      [0xC2,0x6C,0x87], 
				'EEPROM Fault':         [0xA1,0x40,0x46],
                'BT Fault':             [0xA1,0x40,0x49],
				'ESAM Fault':           [0xA1,0x41,0x49],
                'DSRC Fault':           [0xA1,0x42,0x49],
                'UNFIX':                [0xA1,0x43,0x50],       
            }

PCAN_list = {   0x80: [0,True,0],    # rollcounter值  是否第一次=True:one, 出错次数
                               
}

txList = {  
    0x5CF: [0,True,0,8],
    0x5DC: [0,True,0,8],
    0x5E9: [0,True,0,8],
               
}

startCheck = False

MRR_0x66F_data = []
MRR_0x66F_time = []

MRR_0x5F0_data = []



'''
据检索结果，以下NRC在功能寻址下通常被抑制(不响应)： 11 12 7F 7E 31

‌服务不支持‌ (Service Not Supported, SNS) - NRC 0x11
‌当前会话中服务不支持‌ (Service Not Supported In Active Session, SNSIAS) - NRC 0x7F
‌子功能不支持‌ (Sub-Function Not Supported, SFNS) - NRC 0x12
‌当前会话中子功能不支持‌ (Sub-Function Not Supported In Active Session, SFNSIAS) - NRC 0x7E
‌请求超出范围‌ (Request Out Of Range, ROOR) - NRC 0x31
'''